//@ts-check
import fs from 'fs/promises';
import path from 'path';

/**​
  * 将目标package.json的dependencies替换为源package.json的dependencies
  * @param { string } srcPackageJson 源package.json的相对路径
  * @param { string } distPackageJson 目标package.json的相对路径
  */
async function mergeDependencies (srcPackageJson, distPackageJson) {
  try {
    // 解析为绝对路径
    const srcPath = path.resolve(srcPackageJson);
    const distPath = path.resolve(distPackageJson);

    // 读取文件内容
    const srcContent = await fs.readFile(srcPath, 'utf-8');
    const distContent = await fs.readFile(distPath, 'utf-8');

    // 解析为JSON对象
    const srcJson = JSON.parse(srcContent);
    const distJson = JSON.parse(distContent);

    // 替换dependencies
    distJson.dependencies = srcJson.dependencies;

    // 写回目标文件，保持格式（2空格缩进）
    await fs.writeFile(distPath, JSON.stringify(distJson, null, 2));

    console.log('Dependencies merged successfully');
  } catch (error) {
    console.error('Error merging dependencies:', error);
    throw error; // 可以选择重新抛出错误或处理它
  }
}
mergeDependencies('.git/package.json', 'package.json');